package com.example.petproject.util;


import com.example.petproject.constants.Constants;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author admin
 * @deprecated 序列化和反序列化工具
 **/

public class ObjectMapperUtils {

    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        //    指定日期的格式
        SimpleModule module = new SimpleModule();
        module
                //指定localDateTime序列化格式
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(Constants.DateTimeFormat.LOCAL_DATE_TIME)))
                //指定localDateTime反序列化格式
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(Constants.DateTimeFormat.LOCAL_DATE_TIME)));
        objectMapper.registerModule(module);
    }

    /**
     * 序列化，将对象转换成为String字符串
     *
     * @param object 待序列化的对象
     * @return 序列化后的数据
     * @throws JsonProcessingException
     */
    public static String objToString(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    public static <T> T stringToObj(String source, Class<T> tClass) throws JsonProcessingException {
        return objectMapper.readValue(source, tClass);
    }

}
